<template>
     <div class="container">
       <!-- 固定导航 -->
       <van-nav-bar
         fixed
         left-arrow
         @click-left="$router.back()"
         title="小思同学"
       ></van-nav-bar>

       <!-- 聊天主体区域 -->
       <div class="chat-list">
         <div v-for="(item,index) in list" :key="index">
           <!-- 左侧是机器人小思 -->
           <div class="chat-item left" v-if="item.name=='xs'">
             <van-image
               fit="cover"
               round
               src="https://img.yzcdn.cn/vant/cat.jpeg"
             />
             <div class="chat-pao">{{item.msg}}</div>
           </div>

           <!-- 右侧是当前用户 -->
           <div class="chat-item right"  v-else> 
             <div class="chat-pao">{{item.msg}}</div>
             <van-image
               fit="cover"
               round
               :src="$route.query.url"
             />
           </div>
         </div>
       </div>

       <!-- 对话区域 -->
       <div class="reply-container van-hairline--top">
         <van-field placeholder="说点什么..." v-model="word">
           <template #button>
             <span style="font-size:12px;color:#999" @click="fabu">提交</span>
           </template>
         </van-field>
       </div>
     </div>
</template>

<script>
import {io} from 'socket.io-client'
import {getToken} from '@/utils/token.js'
export default {
  name:'chat',
   data() {
       return {
         word: '', // 输入框的内容
         // 所有的聊天消息
         list: [
           // 只根据 name 属性，即可判断出这个消息应该渲染到左侧还是右侧
           { name: 'xs', msg: 'hi，你好！我是小思' },
           { name: 'me', msg: '我是编程小王子' },
         ],
         socket:null   //客户端和服务器端建立连接的对象
       }
     },
     created(){ //在组件初次加载时建立websocket连接对象
        this.socket=io('http://toutiao.itheima.net', {
        query: {
        token: getToken()
      },
      transports: ['websocket']
    })  
    // this.socket.on('connect',()=>{  //测试连接成功
    //     console.log('连接建立成功');
    // })
     //接受后端回来的消息
     this.socket.on('message',(obj)=>{ //绑定一个函数,用来实时监听后端发送过来的数据
          this.list.push({  //如果有数据回来就添加到数组里面,然后进行页面渲染
            name:'xs', msg:obj.msg
          })
     this.$nextTick(()=>{//利用nextTick异步获取元素,这样确保dom元素已经添加,再进行滚动
        let thediv=document.querySelector('.chat-list>div:last-child')  //获取聊天框最后一个元素
          thediv.scrollIntoView({ //让最后一个元素自动滚动到可视区域
          behavior:'smooth'  //表示过度的动画属性
       })
     })
     })
   },
   methods:{
       fabu(){  //发送事件
        if(!this.word) return
           this.socket.emit('message',{  //触发一个函数用来向后端提交数据
             msg:this.word,
             timestamp:new Date().getTime()
           })
           this.list.push({  //并且将自己发送的消息也添加到数组里面进行页面渲染
             name:'me', msg:this.word
           })
       this.$nextTick(()=>{ //利用nextTick异步获取元素,这样确保dom元素已经添加,再进行元素滚动
          let thediv=document.querySelector('.chat-list>div:last-child')  //获取聊天框最后一个元素
          thediv.scrollIntoView({ //让最后一个元素自动滚动到可视区域
          behavior:'smooth'  //表示过度的动画属性
       })
       })
           this.word=''
       }
   },
   destroyed(){ //组件销毁前清除socket实例对象
     this.socket.close()  //将对象置空
     this.socket=null
   }
   }
   </script>

<style lang="less" scoped>
   .container {
     height: 100%;
     width: 100%;
     position: absolute;
     left: 0;
     top: 0;
     box-sizing: border-box;
     background: #fafafa;
     padding: 46px 0 50px 0;
     .chat-list {
       height: 100%;
       overflow-y: scroll;
       .chat-item {
         padding: 10px;
         .van-image {
           vertical-align: top;
           width: 40px;
           height: 40px;
         }
         .chat-pao {
           vertical-align: top;
           display: inline-block;
           min-width: 40px;
           max-width: 70%;
           min-height: 40px;
           line-height: 38px;
           border: 0.5px solid #c2d9ea;
           border-radius: 4px;
           position: relative;
           padding: 0 10px;
           background-color: #e0effb;
           word-break: break-all;
           font-size: 14px;
           color: #333;
           &::before {
             content: '';
             width: 10px;
             height: 10px;
             position: absolute;
             top: 12px;
             border-top: 0.5px solid #c2d9ea;
             border-right: 0.5px solid #c2d9ea;
             background: #e0effb;
           }
         }
       }
     }
   }
   .chat-item.right {
     text-align: right;
     .chat-pao {
       margin-left: 0;
       margin-right: 15px;
       &::before {
         right: -6px;
         transform: rotate(45deg);
       }
     }
   }
   .chat-item.left {
     text-align: left;
     .chat-pao {
       margin-left: 15px;
       margin-right: 0;
       &::before {
         left: -5px;
         transform: rotate(-135deg);
       }
     }
   }
   .reply-container {
     position: fixed;
     left: 0;
     bottom: 0;
     height: 44px;
     width: 100%;
     background: #f5f5f5;
     z-index: 9999;
   }
/deep/.van-nav-bar__content{
       background-color:#007bff
     }
/deep/.van-icon-arrow-left{
      color:white;
     }
   </style>